package net.m510.autosurfer.aeoncard;

import java.net.URI;
import java.util.List;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.m510.autosurfer.common.DocumentPostProcess;
import net.m510.autosurfer.common.exception.InvalidDocumentException;
import net.m510.autosurfer.core.Parameters;
import net.m510.autosurfer.core.utils.AnalyzeUtils;

import org.apache.http.NameValuePair;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.FormElement;
import org.jsoup.select.Elements;

public class AeonCardGoPdfDownload extends DocumentPostProcess {
	private static final Logger log = Logger.getLogger(AeonCardGoPdfDownload.class.getName());

	public AeonCardGoPdfDownload() {
		this(null,null);
	}
	
	public AeonCardGoPdfDownload(CloseableHttpClient client,HttpClientContext context) {
		super(client, context);
		super.log = log;
	}
	
	@Override
	protected URI getUri(Document doc) {
		return URI.create(context.getTargetHost().toURI()).resolve("/NetBranch/seikyuDLInit.do");
	}

	@Override
	protected List<NameValuePair> getRequestParameters(Document doc) {
		final String IMG_ALT="ご請求明細書ダウンロード";
		Elements imgs = doc.select("img[alt="+IMG_ALT+"]");
		if ( imgs.isEmpty() ) throw new InvalidDocumentException("imgタグ "+IMG_ALT+" が見つかりません",doc);
		Element anchor = imgs.first().parent();
		if ( !"a".equalsIgnoreCase(anchor.tagName()) ) throw new InvalidDocumentException("IMGタグの親がAタグではありません"+anchor.toString(),doc);
		String href = anchor.attr("href");
		Pattern ptn = Pattern.compile("javascript:dispatchMonth\\('([0-9]{6})','/NetBranch/seikyuDLInit.do'\\)");
		Matcher m = ptn.matcher(href);
		if ( !m.find() ) throw new InvalidDocumentException("パターン["+ptn+"]が見つかりません"+anchor,doc);
		FormElement form = AnalyzeUtils.getFormElementByName(doc, "detailInquiryForm");
		Parameters p = Parameters.create(form);
		p.put("targetMonth", m.group(1));
		return p.asNameValueList();
	}
}
